package com.shao.proxy.handler;

import com.shao.Configuration;
import com.shao.SrpcBootstrap;
import com.shao.channelHandler.enums.RequestType;
import com.shao.compress.CompressorFactory;
import com.shao.discovery.Registry;
import com.shao.serialize.SerializerFactory;
import com.shao.transport.message.RequestPayload;
import com.shao.transport.message.SrpcRequest;
import com.shao.utils.network.ChannelAndAddressUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/16 17:06
 */
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SrpcConsumerInvocationHandler implements InvocationHandler {

    private Registry registry;

    private Class<?> Interface;

    private final Configuration configuration = SrpcBootstrap.getInstance().getConfiguration();


    @SuppressWarnings("all")
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        // 封装报文
        RequestPayload requestPayLoad = RequestPayload.builder()
                .interfaceName(Interface.getName())
                .methodName(method.getName())
                .parametersType(method.getParameterTypes())
                .parametersValue(args)
                .build();
        SrpcRequest srpcRequest = SrpcRequest.builder()
                .requestId(configuration.getIdGenerator().getId())
                .compressType(CompressorFactory.getCompressor(configuration.getCompressType()).getCode())
                .requestType(RequestType.NORMAL_REQUEST.getType())
                .serializeType(SerializerFactory.getSerializer(configuration.getSerializeType()).getCode())
                .requestPayLoad(requestPayLoad)
                .build();
        SrpcBootstrap.REQUEST_THREAD_LOCAL.set(srpcRequest);

        // 通过服务名查找 ip&port
        InetSocketAddress address = configuration.getLoadBalancer().selectServiceAddress(Interface.getName());
        if (log.isDebugEnabled()) {
            log.debug("服务调用方，发现了服务【{}】，主机为【{}】", Interface.getName(), address);
        }
        // 获取通道
        Channel channel = ChannelAndAddressUtils.getAvalibleChannel(address);

        // 写出报文
        CompletableFuture<Object> completableFuture = new CompletableFuture<>();
        // 暴露 CompletableFutrue
        SrpcBootstrap.PENDING_REQUEST.put(srpcRequest.getRequestId(), completableFuture);
        channel.writeAndFlush(srpcRequest).addListener((ChannelFutureListener) promise -> {
            // 处理异常
            if (!promise.isSuccess()) {
                completableFuture.completeExceptionally(promise.cause());
            }
        });
        SrpcBootstrap.REQUEST_THREAD_LOCAL.remove();
        // 异步
//        AtomicReference<Object> obj = new AtomicReference<>();
//        completableFuture.thenAccept(result -> {
//            log.info("结果：- {}", result);
//            obj.set(result);
//        }).exceptionally(ex -> {
//            log.error("调用RPC失败", ex.getCause());
//            throw new RuntimeException("RPC 超时", ex);
//        });
//        return obj.get();
        // 同步阻塞等待
        try {
            return completableFuture.get(10L, TimeUnit.SECONDS);
        } catch (Exception e) {
            completableFuture.cancel(true);
            throw new RuntimeException("RPC 超时", e);
        }
    }
}
